package com.jblv.frame.common.fastdfs.image;

import com.jblv.frame.common.fastdfs.FastDfsUtils;
import com.jblv.frame.common.fastdfs.fdfs.ByteToInputStream;
import com.jblv.frame.common.fastdfs.fdfs.FastResult;
import com.jblv.frame.common.fastdfs.fdfs.LoadFile;
import com.jblv.frame.common.utils.UUIDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title PictureUtils
 * @projectName jblv-frame
 * @packageName com.jblv.common.fastdfs.image
 * @description PictureUtils
 * @date Create at 2020/5/7 11:00
 * @since jdk1.8
 */


public class PictureUtils {
    private static Logger logger = LoggerFactory.getLogger(PictureUtils.class);
    public static final long PICTURE_MAX_SIZE = 5242880L;
    public static final long CONTRIBUTION_FILE_MAX_SIZE = 2097152L;
    public static final long TASK_FILE_LENGTH = 10485760L;
    public static final long CONTRIBUTION_FILE_LENGTH = 2147483648L;
    public static final String PICTURE_EXTS = ".jpg,.png,.bmp,.jpeg,.svg";
    public static final String FILE_EXTS = ".xls,.xlsx,.pptx,.pdf,.docx,.doc,.ppt,.apk,.txt,.keystore,.mobileprovision,.p12,.zip,.pem,.csv,.jks,.rar,.face-ios,.face-android,.aar,.framework,.bundle,.jar,.a,.mp4,.mp3,.m4a";
    public static final String PICTURE_SIZE_200 = "200_200";
    public static final String PICTURE_SIZE_80 = "80_80";
    public static final String PICTURE_SIZE_48 = "48_48";
    public static final long ORIGINAL_FILE_LENGTH = 52428800L;
    public static final String FILE_EXCEPT_EXTS = ".com,.exe,.scr,.dll,.ocx,.sys,.bat,.vbs,.cmd,.html,.htm,.log,.reg,.ing,.apk,.ipa,.ini,.ico,.inf";
    public static final String ORIGINAL_FILE_EXCEPT_EXTS = ".com,.scr,.dll,.ocx,.sys,.bat,.vbs,.cmd,.html,.htm,.log,.reg,.ing,.ini,.ico,.inf";
    public static final String ZOOM_WIDTH_CONSTRAIN = "_ORIGINAL_";
    private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(20);

    public PictureUtils() {
    }

    public static FastResult cutCustomAndUploadFile(String fileId, CustomPicSize customPicSize) throws Exception {
        new FastResult();
        LoadFile loadFile = FastDfsUtils.downFile(fileId);
        InputStream is = ByteToInputStream.byte2Input(loadFile.getBytes());
        String ext = loadFile.getNameValuePairMap().get("FILE_EXT_NAME");
        File tempFile = File.createTempFile(UUIDGenerator.getUUID(), ext);
        OutputStream outputStream = new FileOutputStream(tempFile);
        ImageUtils.cut(is, customPicSize.getX(), customPicSize.getY(), customPicSize.getWidth(), customPicSize.getHeight(), outputStream);
        FastResult fastResult = FastDfsUtils.uploadFile(tempFile.getAbsolutePath(), ext, (Map)null);
        fastResult.setFilePath(FastDfsUtils.getFilePathById(fastResult.getFileId()));
        tempFile.delete();
        return fastResult;
    }

    public static void main(String[] args) {
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
        System.out.println(UUIDGenerator.getUUID());
    }

    public static List<FastResult> zoom(String sourceFileId, List<PicSize> picSizeDtos) {
        FastResult result = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        List<FastResult> resultList = new ArrayList();
        LoadFile loadFile = FastDfsUtils.downFile(sourceFileId);
        File tempFile = null;
        Iterator var8 = picSizeDtos.iterator();

        while(var8.hasNext()) {
            PicSize picSizeDTO = (PicSize)var8.next();

            try {
                inputStream = new ByteArrayInputStream(loadFile.getBytes());
                String ext = (String)loadFile.getNameValuePairMap().get("FILE_EXT_NAME");
                result = new FastResult();
                tempFile = File.createTempFile(UUIDGenerator.getUUID(), ext);
                outputStream = new FileOutputStream(tempFile);
                int width = picSizeDTO.getWidth();
                int height = picSizeDTO.getHeight();
                if (picSizeDTO.getHeight() == 0) {
                    height = 10000;
                }

                if (picSizeDTO.getWidth() == 0) {
                    width = 10000;
                }

                if (!picSizeDTO.getName().startsWith("_ORIGINAL_") && !picSizeDTO.getName().equals(CommonPictureSizeType.SIZE_720_230.getSizeName())) {
                    ImageUtils.zoom(inputStream, width, height, outputStream);
                } else {
                    ImageUtils.zoomWidthConstrain(inputStream, width, height, outputStream);
                }

                inputStream = new FileInputStream(tempFile);
                String fileId = FastDfsUtils.uploadSubFile(sourceFileId, picSizeDTO.getName(), getByteFormInputStream(inputStream), ext, (Map)null);
                if (fileId == null) {
                    fileId = FastDfsUtils.getSubFileId(sourceFileId, picSizeDTO.getName());
                }

                result.setFileId(fileId);
                result.setFilePath(FastDfsUtils.getFilePathById(fileId));
                resultList.add(result);
            } catch (IOException var22) {
                logger.error("文件读写失败！");
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }

                    if (inputStream != null) {
                        inputStream.close();
                    }

                    if (tempFile != null && tempFile.exists() && tempFile.isFile()) {
                        tempFile.delete();
                    }
                } catch (IOException var21) {
                }

            }
        }

        return resultList;
    }

    public static void asynZoom(String sourceFileId, List<PicSize> picSizeDtos) {
        fixedThreadPool.execute(new ZoomPictureThread(sourceFileId, picSizeDtos));
    }

    public static void asynZoom(String sourceFileId) {
        List<PicSize> picSizeDtos = CommonPictureSizeType.getPicSize();
        fixedThreadPool.execute(new ZoomPictureThread(sourceFileId, picSizeDtos));
    }

    public static void asynZoom(List<FastResult> resultList) {
        List<PicSize> picSizeDtos = CommonPictureSizeType.getPicSize();
        Iterator var2 = resultList.iterator();

        while(var2.hasNext()) {
            FastResult result = (FastResult)var2.next();
            asynZoom(result, picSizeDtos);
        }

    }

    private static void asynZoom(FastResult result, List<PicSize> picSizeDtos) {
        String fileExtName = result.getFileName();
        if (".jpg,.png,.bmp,.jpeg,.svg".contains(fileExtName.toLowerCase())) {
            fixedThreadPool.execute(new ZoomPictureThread(result.getFileId(), picSizeDtos));
        }

    }

    public static void asynZoom(FastResult result) {
        List<PicSize> picSizeDtos = CommonPictureSizeType.getPicSize();
        String fileExtName = result.getFileName();
        if (".jpg,.png,.bmp,.jpeg,.svg".contains(fileExtName.toLowerCase())) {
            fixedThreadPool.execute(new ZoomPictureThread(result.getFileId(), picSizeDtos));
        }

    }

    public static List<FastResult> cutAndUploadFile(String fileId, int x, int y, List<PicSize> picSizeList) {
        List<FastResult> list = new ArrayList();
        LoadFile loadFile = null;
        loadFile = FastDfsUtils.downFile(fileId);
        InputStream is = null;
        String ext = (String)loadFile.getNameValuePairMap().get("FILE_EXT_NAME");
        FastResult fastResult = null;

        try {
            Iterator var9 = picSizeList.iterator();

            while(var9.hasNext()) {
                PicSize picSize = (PicSize)var9.next();
                is = ByteToInputStream.byte2Input(loadFile.getBytes());
                File tempFile = File.createTempFile(UUIDGenerator.getUUID(), ext);
                OutputStream outputStream = new FileOutputStream(tempFile);
                ImageUtils.cut(is, x, y, picSize.getWidth(), picSize.getHeight(), outputStream);
                outputStream.flush();
                outputStream.close();
                fastResult = FastDfsUtils.uploadFile(tempFile.getAbsolutePath(), ext, (Map)null);
                list.add(fastResult);
                tempFile.delete();
                if (is != null) {
                    try {
                        is.close();
                        is = null;
                    } catch (IOException var14) {
                        var14.printStackTrace();
                    }
                }
            }
        } catch (Exception var15) {
            logger.error("文件切割出错");
        }

        return list;
    }

    public static List<FastResult> cutAndUploadFile(List<FastResult> fileIdList, List<PicSize> picSizeList) throws IOException, MyException {
        List<FastResult> list = new ArrayList();
        Iterator var3 = fileIdList.iterator();

        while(var3.hasNext()) {
            FastResult tempResult = (FastResult)var3.next();
            LoadFile loadFile = FastDfsUtils.downFile(tempResult.getFileId());
            InputStream is = ByteToInputStream.byte2Input(loadFile.getBytes());
            String ext = (String)loadFile.getNameValuePairMap().get("FILE_EXT_NAME");
            FastResult fastResult = null;
            Iterator var9 = picSizeList.iterator();

            while(var9.hasNext()) {
                PicSize picSize = (PicSize)var9.next();
                File file = ImageUtils.cut(is, ext, picSize);
                fastResult = FastDfsUtils.uploadFile(file.getAbsolutePath(), ext, (Map)null);
                list.add(fastResult);
            }
        }

        return list;
    }

    public static void coverPicCut(String userUnid, String oldSourceFileId, String newSourceFileId, List<PicSize> picSizeDTOs) {
        boolean modifyFlag = StringUtils.isNotEmpty(oldSourceFileId) && !newSourceFileId.equalsIgnoreCase(oldSourceFileId);
        if (modifyFlag) {
            asynZoom(newSourceFileId, picSizeDTOs);
        }

    }

    public static byte[] getByteFormInputStream(InputStream inputStream) {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        boolean var3 = false;

        int rc;
        try {
            while((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}

